public without sharing class CreateReturnOrderController {

    public ExWarehouse__c exData {set;get;}//可选择的退换明细
    public List<ExWarehouse_Detail__c> details {set;get;}//可选择的退换明细
    public List<ExWarehouse_Detail__c> hasDetails {set; get;}//已经退过的明细
    public List<EXWareHouseDetail>  ds {set;get;}//退换情况
    public String exId {set;get;} // 出库单Id
    public User usr{set;get;}//申请人
    public List<SelectOption> contacts {set;get;}//可选联系人;
    public EXWareBaseInfo baseInfo {set;get;} //退货基础信息;
    public String reId {set;get;}//退货单的Id
    public Boolean isSuccess {get;private set;}//是否保存成功
    
    public CreateReturnOrderController(ApexPages.StandardController stdController) {
        details = new List<ExWarehouse_Detail__c>();
        exId = System.currentPageReference().getParameters().get('id');
        ds = new List<EXWareHouseDetail>();
        exData = new ExWarehouse__c();
		baseInfo = new EXWareBaseInfo();
        contacts = new List<SelectOption>();
        isSuccess = false;
  
      }
 
     public void init(){
      usr = [select id,name,SubCompanyManager__r.name , ManagerId from User where id =: System.UserInfo.getUserId()];
        baseInfo.applicatePerson = usr.name;


         // 获取出库单数据
        Schema.DescribeSobjectResult ed = ExWarehouse__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fm = ed.fields.getMap();          
        String sql0 = 'select ';
        sql0 += fieldMap(fm);
        sql0 += '  from ExWarehouse__c where  Id = \'' + exId + '\'';
        exData = Database.query(sql0);
          //获取联系人
         //System.debug(exData.Account__c);
         for(Contact c : [select name from Contact where AccountId =:exData.Account__c ]){
         	contacts.add(new SelectOption(c.name, c.name));
         }
        
          //System.debug('======='+contacts);

         // 获取出库明细
        Schema.DescribeSobjectResult m = ExWarehouse_Detail__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fm1 = m.fields.getMap();          
        String sql = 'select ';
        sql += fieldMap(fm1);
        sql += ', Product__r.Name,Product__r.Brand__c,Product__r.Spec__c,Product__r.BatchNumber__c,Product__r.Model__c from ExWarehouse_Detail__c where  ExWarehouse__c = \'' + exId + '\'';
        details = Database.query(sql);
         
        //获取退货订单数据
         List <ExWarehouse__c> reOrs = [select Id from ExWarehouse__c where ReturnRelationExhouse__c =: exId];
         List<String> ids = new List<String>();
         for(ExWarehouse__c r : reOrs){
         	ids.add(r.Id);
         }
         //System.debug(ids);
        //获取退货订单明细
         hasDetails = [select Id,Product__c,ReturnNum__c from ExWarehouse_Detail__c where ExWarehouse__c in : ids];
        /* 
        Schema.DescribeSobjectResult t = ExWarehouse__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fm2 = t.fields.getMap();
        String sql1 = 'select ';
        sql1 += fieldMap(fm2);
        sql1 += ' from ExWarehouse_Detail__c where ExWarehouse__c = \'' + exId + '\'';
        System.debug(sql1); 
        hasDetails =  Database.query(sql1);
        */
         ///计算已经退换产品的数量
        Map<String,Decimal> reMap = new   Map<String,Decimal>();
        for (ExWarehouse_Detail__c r : hasDetails){

            if(reMap.containsKey(r.Product__c)){
                reMap.put(r.Product__c,reMap.get(r.Product__c) + r.ReturnNum__c);
            }else{
                reMap.put(r.Product__c,r.ReturnNum__c);
            }
        }
        for(ExWarehouse_Detail__c d : details){
            EXWareHouseDetail e = new EXWareHouseDetail();
            e.ex = d;
            e.isReturning = false;
            e.willReturnNum = '0';
            if(reMap.containsKey(d.Product__c)){
                e.hasReturnNum = reMap.get(d.Product__c);
                e.returnNum = d.nnum__c - reMap.get(d.Product__c);
            }else{
            	e.hasReturnNum = 0.0;
                e.returnNum = d.nnum__c;
            }
            
            ds.add(e);
        } 
     }
    public void save1(){
      
        SavePoint sp = Database.setSavePoint();
        try{
            //生成退货订单
            List<ExWarehouse_Detail__c> reOrs = new List<ExWarehouse_Detail__c>();
            ExWarehouse__c order = new ExWarehouse__c() ;
       		order.IsReturnOrder__c = true ;//设定为退换订单;
       		order.ReturnRelationExhouse__c = exData.Id;//关联出库单
			//order.OwnerId=usr.Id;
           // order.Name='RG'+exData.Name;
            order.Approve_Status__c = '草稿中';
            order.RecordTypeId = Utils.getRecordTypeIdByDevNameAndObjName('退货申请单', 'ExWarehouse__c');
            //order.SystemModstamp=exData.SystemModstamp;
            //order.LastViewedDate=exData.LastViewedDate;
           // order.LastReferencedDate=exData.LastReferencedDate; 
            order.Account__c=exData.Account__c; 
            order.cbiztype__c=exData.cbiztype__c;
            order.cgeneralhid__c=exData.cgeneralhid__c;
            order.ck__c=exData.ck__c;
            order.corpcode__c=exData.corpcode__c;
            order.corpname__c=exData.corpname__c;
            order.currtypename__c=exData.currtypename__c;
            order.custcode__c=exData.custcode__c; 
            order.custname__c=exData.custname__c;
            order.dbilldate__c=exData.dbilldate__c; 
            order.deptname__c=exData.deptname__c;
            order.isfq__c=exData.isfq__c; 
            order.iszx__c=exData.iszx__c;
            order.kpfs__c=exData.kpfs__c;
            order.memo__c='';//备注
            order.ntaxrate__c=exData.ntaxrate__c; 
            order.sflx__c=exData.sflx__c; 
            order.xsqy__c=exData.ywyname__c;
            order.ywyname__c=exData.ywyname__c; 
            order.zdkh__c=exData.zdkh__c;
            ///基础信息
            
           // order.Finance__c = baseInfo.finance;
            order.isReturnInvoice__c = baseInfo.isReinvoice;
            order.TransferNumber__c = baseInfo.TransferNumber;
            order.ReturnReason__c = baseInfo.reason;
            order.ReturnOtherReason__c = baseInfo.otherReason;
            order.invoiceNumber__c = baseInfo.invoiceNumber;
            order.Contact__c = baseInfo.contact;
            order.Applicant__c = baseInfo.applicatePerson;
            //order.ApprovalPerson__c = baseInfo.approvalPerson;
            order.returnTransportFee__c = baseInfo.returnTransportFee;
            //order.DetailSize__c=exData.DetailSize__c; 
            
        	System.debug(order);
        	upsert order;
        	///生成
        	for(EXWareHouseDetail ex :ds){
			if(ex.isReturning == true){
                 system.debug('来了');
				system.debug(ex.willReturnNum);
            	ExWarehouse_Detail__c r =  ex.ex.clone(false,true);
                r.IsReturnDetail__c = true;///设定为退换明细;
                r.ExWarehouse__c = order.Id; ///关联退换订单;
                r.ReturnNum__c = Double.valueOf(ex.willReturnNum);
                r.RecordTypeId = Utils.getRecordTypeIdByDevNameAndObjName('退货单明细', 'ExWarehouse_Detail__c');
               /* 
                //r.IsDeleted=ex.ex.IsDeleted; 
                r.Name='RGD'+ex.ex.Name;
                //r.SystemModstamp=ex.ex.SystemModstamp; 
                r.ExWarehouse__c=ex.ex.ExWarehouse__c; 
                r.Product__c=ex.ex.Product__c;
                r.sale_hid__c=ex.ex.sale_hid__c;
                r.salecode__c=ex.ex.salecode__c;
                r.outcode__c=ex.ex.outcode__c; 
                r.vreceiveaddress__c=ex.ex.vreceiveaddress__c; 
                r.dbizdate__c=ex.ex.dbizdate__c;
                r.invcode__c=ex.ex.invcode__c;
                r.invdm__c=ex.ex.invdm__c;
                r.cinvbasid__c=ex.ex.cinvbasid__c; 
                r.invshortname__c=ex.ex.invshortname__c; 
                r.invname__c=ex.ex.invname__c;
                r.jldw__c=ex.ex.jldw__c;
                r.invspec__c=ex.ex.invspec__c;
                r.csourcetype__c=ex.ex.csourcetype__c; 
                r.mk01__c=ex.ex.mk01__c;
                r.vbatchcode__c=ex.ex.vbatchcode__c; 
                r.invpinpai__c=ex.ex.invpinpai__c;
                r.dproducedate__c=ex.ex.dproducedate__c;
                r.dvalidate__c=ex.ex.dvalidate__c;
                r.nnum__c=ex.ex.nnum__c; 
                r.nquotemny__c=ex.ex.nquotemny__c; 
                r.mk2__c=ex.ex.mk2__c; 
                r.noriginalcursummny__c=ex.ex.noriginalcursummny__c; 
                r.sale_bid__c=ex.ex.sale_bid__c;
                r.invtype__c=ex.ex.invtype__c; 
                r.nshouldoutnum__c=ex.ex.nshouldoutnum__c; 
               	r.cfirsttype__c=ex.ex.cfirsttype__c;
                //r.cgeneralhid__c=ex.ex.cgeneralhid__c;
                r.dr__c=ex.ex.dr__c;
                */
      
             reOrs.add(r); 
               // system.debug(r);
          	  }  
        	}
           System.debug('第二个' + reOrs);

            insert reOrs;
        // return new PageReference('/'+roId);

			
            reId = order.Id;
		 System.debug('成功'+ reId);
            isSuccess = true;
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,
                                     'OK：'));
        }catch(Exception e){
         //System.debug('失败');
         Database.rollback(sp);
		isSuccess = false;
    	ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,
                                     '操作出错：'+e.getMessage()));
        }

       // return new PageReference('/'+exId);

    }
    
    private String fieldMap( Map<String,Schema.SObjectField> fm ){
         String fields = '';
        for (String field : fm.keySet()) {
            if (fields.length() > 0) {
                fields += ', '; 
            }
            fields += field;
        }
        return fields;

    }
    public Class EXWareHouseDetail{
    	public ExWarehouse_Detail__c ex {get;set;}
        public Decimal hasReturnNum {get;set;}///已经或真在退换的数量
        public Decimal returnNum {get;set;}//剩余数量
      	public String willReturnNum {get;set;}//将要退换数量
        public Boolean isReturning {get;set;}//是否要退换

    }
    public Class EXWareBaseInfo{
        //public String deptManager {set;get;}//部门主管
    	//public String finance {set;get;}//财务部
        public Boolean isReinvoice {set;get;}//是否退发票
        public String TransferNumber {set;get;}//调拨单号
        public String reason {set;get;}//退货原因
        public String otherReason {set;get;}//其他原因
        public String invoiceNumber {set;get;}//发票单号
        public Decimal returnTransportFee {set;get;}//退回运费
        public String applicatePerson {set;get;}//申请人
       // public String approvalPerson {set;get;}//审批人;
        public String contact {set;get;}//联系人;
    }
}